package com.smartrobot.smartrobot.activity;

import java.io.File;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.AssetManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.Spinner;
import android.widget.TextView;

import com.smartrobot.smartrobot.R;
import com.smartrobot.smartrobot.util.CityModel;
import com.smartrobot.smartrobot.util.DistrictModel;
import com.smartrobot.smartrobot.util.FileUtil;
import com.smartrobot.smartrobot.util.HttpUtil;
import com.smartrobot.smartrobot.util.ImageUtil;
import com.smartrobot.smartrobot.util.Organ;
import com.smartrobot.smartrobot.util.PictureFromCammera;
import com.smartrobot.smartrobot.util.ProvinceModel;
import com.smartrobot.smartrobot.util.User;
import com.smartrobot.smartrobot.util.XmlParserHandler;
import com.smartrobot.smartrobot.view.ToastCustom;


public class CretaOrganActivity extends Activity implements OnClickListener{
	
	private TextView name;
	private ImageView businessLicense,identifyCard,back;
	private TextView create;
	private Drawable initDrawable;
	private String path;
	private Spinner provinceSpinner,citySpinner,areaSpinner;
	private EditText inputPos;
    private Organ organ;
	
	private CretaOrganHandler handler = new CretaOrganHandler();
	
	private String businessPath;
	private String identifyPath;
	
	private ArrayAdapter provinceAdapter;
	private ArrayAdapter cityAdapter;
	private ArrayAdapter areaAdapter;
    private TextView progressTxt;

    private boolean isCreatingOrgan = false;
	
	/**
	 * 所有省
	 */
	protected String[] mProvinceDatas;
	/**
	 * key - 省 value - 市
	 */
	protected Map<String, String[]> mCitisDatasMap = new HashMap<String, String[]>();
	/**
	 * key - 市 values - 区
	 */
	protected Map<String, String[]> mDistrictDatasMap = new HashMap<String, String[]>();
	
	/**
	 * key - 区 values - 邮编
	 */
	protected Map<String, String> mZipcodeDatasMap = new HashMap<String, String>(); 

	/**
	 * 当前省的名称
	 */
	protected String mCurrentProviceName;
	/**
	 * 当前市的名称
	 */
	protected String mCurrentCityName;
	/**
	 * 当前区的名称
	 */
	protected String mCurrentDistrictName ="";
	
	/**
	 * 当前区的邮政编码
	 */
	protected String mCurrentZipCode ="";
	
	/**
	 * 解析省市区的XML数据
	 */
	
	
	int area[] = new int[]{
		R.array.beijing,R.array.guangzhou,R.array.shanghai	
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
        if(savedInstanceState != null){
            throw new NullPointerException();
        }
		this.setContentView(R.layout.page_create_organ);
		
		initProvinceDatas();
        HttpUtil.init(getApplicationContext());
		init();
		
		
	}
	
	@SuppressLint("NewApi") 
	void init(){
		
		initDrawable = this.getResources().getDrawable(R.drawable.ic_launcher);
		
		name = (TextView)findViewById(R.id.create_organ_organName); 
		businessLicense = (ImageView)findViewById(R.id.create_organ_bussinLicense);
		identifyCard  = (ImageView)findViewById(R.id.create_organ_identifyCard);
		create = (TextView)findViewById(R.id.create_organ_create);
		back = (ImageView)findViewById(R.id.create_organ_back);
		provinceSpinner = (Spinner)findViewById(R.id.create_organ_provice);
		citySpinner  = (Spinner)findViewById(R.id.create_organ_city);
		areaSpinner  = (Spinner)findViewById(R.id.create_organ_area);
		inputPos = (EditText)findViewById(R.id.create_organ_address_detail);
        progressTxt = (TextView)findViewById(R.id.create_organ_create);

		
		
		back.setOnClickListener(this);
		create.setOnClickListener(this);
		businessLicense.setOnClickListener(this);
		identifyCard.setOnClickListener(this);
		
		businessLicense.setImageDrawable(initDrawable);
		identifyCard.setImageDrawable(initDrawable);
		
		
		// 初始化adapter
		provinceAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item,
				                                                                     mProvinceDatas);
		provinceAdapter
						.setDropDownViewResource(android.R.layout.simple_list_item_single_choice);
		provinceSpinner.setAdapter(provinceAdapter);
		provinceSpinner.setOnItemSelectedListener(new ProvinceListener());
		
	}

	@Override
	public void onClick(View v) {
		
		if(v.getId() == create.getId()){
			
			switch(legalCreateOrgan()){
			
			case 1:
				ToastCustom.showToast(getApplicationContext(), "店名称不为空且最多20位");
				break;
				
			case 2:
				ToastCustom.showToast(getApplicationContext(), "必须提交工商执照照片");
				break;
				
			case 3:
				ToastCustom.showToast(getApplicationContext(), "必须提交身份证图片");
				break;
				
			case 4:
				ToastCustom.showToast(getApplicationContext(), "请登录后再来注册店铺");
				break;
			default:

                try{
                    FileUtil.deleteFile(new File(FileUtil.detailCachePath));
                    FileUtil.deleteFile(new File(FileUtil.storeActiveCachePathName));
                }catch (Exception e){
                    e.printStackTrace();
                }

				if(!businessPath.equals("") && !identifyPath.equals("") && User.getInstance() != null){
					organ = new Organ();
					organ.setMasterId(User.getInstance().getId());
					organ.setMasterAccount(User.getInstance().getPhone());
					organ.setName(name.getText().toString());
					organ.setBusinessLiense(businessPath);
					organ.setIdentifyCard(identifyPath);
					organ.setProvince(mCurrentProviceName);
					organ.setCity(mCurrentCityName);
					organ.setArea(mCurrentDistrictName);

					organ.setPostCode(mCurrentZipCode);
					String input = inputPos.getText().toString();
					if(input != null)
				        organ.setAddress(mCurrentProviceName+mCurrentCityName+mCurrentDistrictName+input);
					else
						organ.setAddress(mCurrentProviceName+mCurrentCityName+mCurrentDistrictName+"");

                    InputMethodManager imm= (InputMethodManager) getSystemService(this.INPUT_METHOD_SERVICE);
                    imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(),
                            InputMethodManager.HIDE_NOT_ALWAYS);

                    if(!isCreatingOrgan){
                        isCreatingOrgan = true;
                        HttpUtil.apiRegisterOrgan(organ, handler);
                        progressTxt.setText("正在提交");

                    }



				}else{
					ToastCustom.showToast(getApplicationContext(), "获取图片路径失败！");
				}
				
				
				break;
				
			}
		}
		
		if( v.getId() == identifyCard.getId() || v.getId() == businessLicense.getId()){
			showMenuDialog(v.getId());
		}
		
		if(v.getId() == back.getId()){
			this.finish();
		}
		
	}
	
	int legalCreateOrgan(){
		
		if(name.getText().toString().length() < 1 || name.getText().toString().length() > 20)
			return 1;
		if( initDrawable == businessLicense.getDrawable() )
			return 2;
		if(initDrawable == identifyCard.getDrawable())
			return 3;
		if(User.getInstance() == null || User.getInstance().getPhone().equals("未填写"))
			return 4;
		
		
		return 10;
	}
	
	void showMenuDialog(final int id){
		AlertDialog.Builder dialog = new AlertDialog.Builder(CretaOrganActivity.this);
		dialog.setTitle("选项")
				.setItems(R.array.photoMenu,
						new AlertDialog.OnClickListener() {

							public void onClick(DialogInterface dialog,
									int which) {
								switch (which) {
								case 0:// 选择从照相机中获取
									if(id == identifyCard.getId())
									{
										path = ImageUtil.getCameraPic(CretaOrganActivity.this,ImageUtil.IMAGE_FROM_CAMMERA_IDENTIFY);
									}else{
										path = ImageUtil.getCameraPic(CretaOrganActivity.this,ImageUtil.IMAGE_FROM_CAMMERA_BUSINESS);
									}
									break;
								case 1:// 选择从文件夹中获取
									if(id == identifyCard.getId()){
										ImageUtil.getDirPic(CretaOrganActivity.this, ImageUtil.IMAGE_FROM_FILE_IDENTIFY);
									}else
										ImageUtil.getDirPic(CretaOrganActivity.this,ImageUtil.IMAGE_FROM_FILE_BUSINESS);
									break;
								}
							}
						}).show();
	}
	
	
	class CretaOrganHandler extends Handler{
		@Override
		public void dispatchMessage(Message msg) {

            progressTxt.setText("提交");

			switch(msg.what){
			
			case HttpUtil.CREATEORGAN_SUCCESS:




                isCreatingOrgan = false;
				ToastCustom.showToast(getApplicationContext(), "店铺资料提交成功，等待后台审核后...");
                CretaOrganActivity.this.setResult(RESULT_OK, null);
                FileUtil.deleteFile(new File(FileUtil.detailCachePath));
                FileUtil.deleteFile(new File(FileUtil.storeActiveCachePathName));
                CretaOrganActivity.this.finish();

		     break;
		     
			case HttpUtil.CREATEORGAN_FAILD:
                isCreatingOrgan = false;
             // 判断店铺存在后，显示错误
                if(msg.obj != null){

                    if(msg.obj.equals("4")){
                        ToastCustom.showToast(getApplicationContext(), "店铺已经存在！");
                    }else if(msg.obj.equals("100")){

                        HttpUtil.reLogin(getApplication(),handler);

                    }else{
                        ToastCustom.showToast(getApplicationContext(), "连接服务器失败，请稍后再试!");
                    }

                }
				
				break;

                case HttpUtil.LOGIN_SUCCESS:

                    HttpUtil.apiRegisterOrgan(organ,handler);

                    break;

                case HttpUtil.LOGIN_FAILD:

                    ToastCustom.showToast(getApplicationContext(),"连接服务失败，请稍后再试!");

                    break;
			
			
			}
			
		}
	}
	
	
	
	
	// 返回 请求资源
		public void onActivityResult(int requestCode, int resultCode, Intent data) {

			if (requestCode == ImageUtil.IMAGE_FROM_CAMMERA_IDENTIFY || 
					requestCode == ImageUtil.IMAGE_FROM_CAMMERA_BUSINESS) {// 照相机返回路径
				if (resultCode == RESULT_OK) { // 返回成功

					if(path != null && !path.equals(""))
		            {
						if(requestCode == ImageUtil.IMAGE_FROM_CAMMERA_BUSINESS)
						  {
							Bitmap businessPic = PictureFromCammera.scaleBitmap(path);
							businessLicense.setImageBitmap(businessPic);
							
							// 设置文件保存位置
							String fileName = FileUtil.businessPic;
							//文件真正位置
							String filePath = FileUtil.PHONE_DIR_INNER + FileUtil.PICTURE
									+ fileName;
							
							if (FileUtil.createFile(filePath)) {
								// 只有将图片保存到SdCard里面才可以完成上传
								if (FileUtil.writeBitmapToSDCard(filePath,businessPic))
									businessPath = filePath;
								else businessPath = "";
							}
							
							
						  }
						else
						  {
							
							Bitmap identifyPic = PictureFromCammera.scaleBitmap(path);
							identifyCard.setImageBitmap(identifyPic);
							
//							// 设置文件保存位置
							String fileName = FileUtil.identifyCard;
							//文件真正位置
							String filePath = FileUtil.PHONE_DIR_INNER + FileUtil.PICTURE
									+ fileName;
							
							if (FileUtil.createFile(filePath)) {
								// 只有将图片保存到SdCard里面才可以完成上传
								if (FileUtil.writeBitmapToSDCard(filePath,identifyPic))
									identifyPath = filePath;
								else identifyPath = "";
							}
							
						  }
		            }else{
		            	ToastCustom.showToast(getApplicationContext(), "没有找到图片，请重新选择");
		            }

				}
			}

			if (requestCode == ImageUtil.IMAGE_FROM_FILE_IDENTIFY
					|| requestCode == ImageUtil.IMAGE_FROM_FILE_BUSINESS) {// 打开文件返回路径
				if (resultCode == RESULT_OK) { // 返回成功
			        try {
			            Uri uri=data.getData();
			            //获取封装相册图像的数据
			            Cursor cursor=getContentResolver().query(uri, null, null, null, null);
			            cursor.moveToFirst();
			            //获取选中相册的文件路径
			            path=cursor.getString(1);
			            cursor.close();
			            if(path != null){
			            	if(path.equals(""))
			            		ToastCustom.showToast(getApplicationContext(), "没有找到图片，请重新选择");
							else
							if(requestCode == ImageUtil.IMAGE_FROM_FILE_BUSINESS)
								  {
								Bitmap businessPic = PictureFromCammera.scaleBitmap(path);
								businessLicense.setImageBitmap(businessPic);
								
								// 设置文件保存位置
								String fileName = FileUtil.businessPic;
								//文件真正位置
								String filePath = FileUtil.PHONE_DIR_INNER + FileUtil.PICTURE
										+ fileName;
								
								if (FileUtil.createFile(filePath)) {
									// 只有将图片保存到SdCard里面才可以完成上传
									if (FileUtil.writeBitmapToSDCard(filePath,businessPic))
										businessPath = filePath;
									else businessPath = "";
								}
								  }
								else
								  {
									Bitmap identifyPic = PictureFromCammera.scaleBitmap(path);
									identifyCard.setImageBitmap(identifyPic);
									
									// 设置文件保存位置
									String fileName = FileUtil.identifyCard;
									//文件真正位置
									String filePath = FileUtil.PHONE_DIR_INNER + FileUtil.PICTURE
											+ fileName;
									
									if (FileUtil.createFile(filePath)) {
										// 只有将图片保存到SdCard里面才可以完成上传
										if (FileUtil.writeBitmapToSDCard(filePath,identifyPic))
											identifyPath = filePath;
										else identifyPath = "";
									}
								  }
				            }else
				            	ToastCustom.showToast(getApplicationContext(), "没有找到图片，请重新选择");
			        } catch (Exception e)
			        {
			            // TODO Auto-generated catch block
			            e.printStackTrace();
			        }
				}
			}
		}
		//点击其他地方隐藏键盘
		@Override  
	    public boolean onTouchEvent(MotionEvent event) {  
	        // TODO Auto-generated method stub  
	        if (event.getAction() == MotionEvent.ACTION_DOWN) {  
	            System.out.println("down");  
	            if (this.getCurrentFocus() != null) {  
	                if (this.getCurrentFocus().getWindowToken() != null) {  
	                	InputMethodManager imm= (InputMethodManager) getSystemService(this.INPUT_METHOD_SERVICE);
	                    imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(),  
	                            InputMethodManager.HIDE_NOT_ALWAYS);  
	                }  
	            }
	            else
	            	ToastCustom.showToast(getApplicationContext(), "没有找到图片，请重新选择");
	        }  
	        return super.onTouchEvent(event);  
	    }

		
		class ProvinceListener implements OnItemSelectedListener{

			/**
			 * 监听 选择的城市，显示相应的城市
			 */
			@Override
			public void onItemSelected(AdapterView<?> parent, View view, int position,
					long id) {
				
					mCurrentProviceName = mProvinceDatas[position];
					String[] cities = mCitisDatasMap.get(mCurrentProviceName);
					if (cities == null) {
						cities = new String[] { "" };
					}
					
					System.out.println("选择");
					
					// 初始化adapter
					cityAdapter = new ArrayAdapter<String>(CretaOrganActivity.this, android.R.layout.simple_spinner_dropdown_item,cities);
					cityAdapter.setDropDownViewResource(android.R.layout.simple_list_item_single_choice);
					citySpinner.setAdapter(cityAdapter);
					citySpinner.setOnItemSelectedListener(new cityListener());
					
				
				
			}

			@Override
			public void onNothingSelected(AdapterView<?> parent) {
				// TODO Auto-generated method stub
				
			}
		}
		
		class cityListener implements OnItemSelectedListener{

			/**
			 * 监听 选择的城市，显示相应的城市
			 */
			@Override
			public void onItemSelected(AdapterView<?> parent, View view, int position,
					long id) {
				
					
					mCurrentCityName = mCitisDatasMap.get(mCurrentProviceName)[position];
					String[] areas = mDistrictDatasMap.get(mCurrentCityName);
	
					if (areas == null) {
						areas = new String[] { "" };
					}
					
					// 初始化adapter
					areaAdapter = new ArrayAdapter<String>(CretaOrganActivity.this, android.R.layout.simple_spinner_dropdown_item,areas);
					areaAdapter.setDropDownViewResource(android.R.layout.simple_list_item_single_choice);
					areaSpinner.setAdapter(areaAdapter);
					areaSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
					

						@Override
						public void onItemSelected(AdapterView<?> parent,
								View view, int position, long id) {
							
							mCurrentDistrictName = mDistrictDatasMap.get(mCurrentCityName)[position];
							mCurrentZipCode = mZipcodeDatasMap.get(mCurrentDistrictName);
							
						}

						@Override
						public void onNothingSelected(AdapterView<?> parent) {
							// TODO Auto-generated method stub
							
						}
						
					});
				
			}

			@Override
			public void onNothingSelected(AdapterView<?> parent) {
				// TODO Auto-generated method stub
				
			}
		}
		
	    protected void initProvinceDatas()
		{
			List<ProvinceModel> provinceList = null;
	    	AssetManager asset = getAssets();
	        try {
	            InputStream input = asset.open("province_data.xml");
	            // 创建一个解析xml的工厂对象
				SAXParserFactory spf = SAXParserFactory.newInstance();
				// 解析xml
				SAXParser parser = spf.newSAXParser();
				XmlParserHandler handler = new XmlParserHandler();
				parser.parse(input, handler);
				input.close();
				// 获取解析出来的数据
				provinceList = handler.getDataList();
				//*/ 初始化默认选中的省、市、区
				if (provinceList!= null && !provinceList.isEmpty()) {
					mCurrentProviceName = provinceList.get(0).getName();
					List<CityModel> cityList = provinceList.get(0).getCityList();
					if (cityList!= null && !cityList.isEmpty()) {
						mCurrentCityName = cityList.get(0).getName();
						List<DistrictModel> districtList = cityList.get(0).getDistrictList();
						mCurrentDistrictName = districtList.get(0).getName();
						mCurrentZipCode = districtList.get(0).getZipcode();
					}
				}
				//*/
				mProvinceDatas = new String[provinceList.size()];
	        	for (int i=0; i< provinceList.size(); i++) {
	        		// 遍历所有省的数据
	        		mProvinceDatas[i] = provinceList.get(i).getName();
	        		List<CityModel> cityList = provinceList.get(i).getCityList();
	        		String[] cityNames = new String[cityList.size()];
	        		for (int j=0; j< cityList.size(); j++) {
	        			// 遍历省下面的所有市的数据
	        			cityNames[j] = cityList.get(j).getName();
	        			List<DistrictModel> districtList = cityList.get(j).getDistrictList();
	        			String[] distrinctNameArray = new String[districtList.size()];
	        			DistrictModel[] distrinctArray = new DistrictModel[districtList.size()];
	        			for (int k=0; k<districtList.size(); k++) {
	        				// 遍历市下面所有区/县的数据
	        				DistrictModel districtModel = new DistrictModel(districtList.get(k).getName(), districtList.get(k).getZipcode());
	        				// 区/县对于的邮编，保存到mZipcodeDatasMap
	        				mZipcodeDatasMap.put(districtList.get(k).getName(), districtList.get(k).getZipcode());
	        				distrinctArray[k] = districtModel;
	        				distrinctNameArray[k] = districtModel.getName();
	        			}
	        			// 市-区/县的数据，保存到mDistrictDatasMap
	        			mDistrictDatasMap.put(cityNames[j], distrinctNameArray);
	        		}
	        		// 省-市的数据，保存到mCitisDatasMap
	        		mCitisDatasMap.put(provinceList.get(i).getName(), cityNames);
	        	}
	        } catch (Throwable e) {  
	            e.printStackTrace();  
	        } finally {
	        	
	        } 
		}
		


	
}


